﻿namespace CatFax.Service.WebRole
{
    using System;
    using System.ServiceModel;
    using System.Xml.Linq;
    using CatFax.Entities;
    using Microsoft.Samples.ServiceHosting.StorageClient;
    using Microsoft.ServiceHosting.ServiceRuntime;

    // NOTE: If you change the class name "AuditRowService" here, you must also update the reference to "AuditRowService" in Web.config.
    /// <summary>
    /// The main class for the service
    /// </summary>
    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class AuditRowService : IAuditRowService
    {
        public void AddAuditRow(string partitionKey, string rowKey, string displayData, string rowData)
        {
            try
            {
                StorageAccountInfo accountInfo = StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorageEndpoint");
                var context = new AuditRowEntityDataServiceContext(accountInfo);
                context.AddAuditRowEntity(partitionKey, rowKey + "-" + AuditRowIndexer.GetNextSeqForRow(partitionKey, rowKey), rowData, displayData);
            }
            catch (Exception ex)
            {
                RoleManager.WriteToLog("Error", ex.ToString());
            }
        }

        public string GetAuditRowData(string partitionKey, string rowKey)
        {
            var rowData = new XElement("auditRowData");
            StorageAccountInfo accountInfo = StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorageEndpoint");

            var indexContext = new AuditRowIndexEntityDataServiceContext(accountInfo);
            if (indexContext.Exists(rowKey))
            {
                AuditRowIndexEntity auditRowIndexEntity = indexContext.GetSingleRow(rowKey);
                rowKey += "-" + auditRowIndexEntity.LastSeq;
            }
            else
            {
                rowKey += "-1";
            }

            var context = new AuditRowEntityDataServiceContext(accountInfo);
            if (context.Exists(rowKey, partitionKey))
            {
                AuditRowEntity auditRowEntity = context.GetSingleRow(rowKey, partitionKey);
                rowData.Add(new XAttribute("result", "1 row(s) returned"));
                rowData.Add(XElement.Parse(auditRowEntity.RowData));
            }
            else
            {
                rowData.Add(new XAttribute("result", "No data found"));
            }

            return rowData.ToString();
        }
    }
}
